package net.sql.config;

import java.io.File;
import java.io.FileFilter;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

import org.dom4j.Document;
import org.dom4j.Element;

import net.dotool.Dom4jTools;
import net.dotool.IoTools;
import net.dotool.file.SimpleWatch;
import net.dotool.file.WatchTools;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com
 * @date 2018年5月2日上午11:35:12
 */
public abstract class AbstractXmlParser {
	private String path;
	private String fileName;
	private boolean watchDir;

	public void initXml(String path, String fileName, boolean watchDir) {
		this.path = path;
		this.fileName = fileName;
		this.watchDir = watchDir;
		if (watchDir) {
			watchDir();
		} else {
			watchFile();
		}
	}

	public String getPath() {
		return path;
	}

	private void watchDir() {
		new File(getPath()).listFiles(new FileFilter() {
			public boolean accept(File file) {
				loadConfig(file);
				return false;
			}
		});
		WatchTools.watchDir(getPath(), new SimpleWatch() {
			public void onModify(WatchEvent<?> event, Path currentPath) {
				String fileName = currentPath.getFileName().toString();
				loadConfig(new File(getPath() + File.separator + fileName));
			}
		}).start();
	}

	private void watchFile() {
		final String filePath = getPath() + File.separator + fileName;
		WatchTools.watchFile(filePath, new SimpleWatch() {
			public void onModify(WatchEvent<?> event, Path currentPath) {
				loadConfig(new File(filePath));
			}

		}).start();
		loadConfig(new File(filePath));
	}

	/**
	 * 加载配置文件
	 */
	private void loadConfig(File filePath) {
		try {
			if (filePath.isDirectory())
				return;
			String preName = IoTools.getFileNameWithoutExtendsion(filePath.getName());
			if (preName == null)
				return;
			// 如果是监控目录，需要过滤文件
			if (watchDir && !preName.contains(fileName)) {
				return;
			}
			final Document doc = Dom4jTools.createDocument(filePath);
			parser(preName, doc.getRootElement());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected abstract void parser(String fileName, Element rootElement);

}
